package com.sgb.kjwl.view.ui.activity.self.packers;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.ScreenUtils;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivitySelfTeamAchieveEditBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.self.SelfTeamAchieveEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.ui.activity.PhotoViewActivity;
import com.sgb.link.view.adapter.SelfTeamPicAdapter;
import com.sgb.kjwl.view.ui.adapter.self.packers.SelfTeamVideoAdapter;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.viewmodel.self.packers.SelfTeamAchieveEditModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MToast;

import java.io.File;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 *description:添加工程业绩或编辑工程业绩
 * @author WYJ
 * @date 2020/8/28
 */
public class SelfTeamAchieveEditActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    @Inject
    SelfTeamAchieveEditModel mModel;
    private ActivitySelfTeamAchieveEditBinding mBind;

    private SelfTeamAchieveEntity mEntity;
    private SelfTeamPicAdapter mPicAdapter;
    private List<String> mUploadImgList;
    /**
     * 防止重复上传
     */
    private Map<String, String> mCacheImgMap;
    private int mCurPicNum;

    private SelfTeamVideoAdapter mVideoAdapter;
    private List<String> mUploadVideoList;
    /**
     * 一级联动数据
     */
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    /**
     * 二级联动数据
     */
    private final List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    /**
     * 三级联动数据
     */
    private final List<List<List<AddressEntity>>> opt3 = new ArrayList<>();
    private int cityPosition1;
    private int cityPosition3;
    private int cityPosition2;

    public static void start(AppCompatActivity context, SelfTeamAchieveEntity entity, int code) {
        Intent intent = new Intent(context, SelfTeamAchieveEditActivity.class);
        intent.putExtra(AppConstant.EXTRA_ENTITY, entity);
        context.startActivityForResult(intent, code);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mEntity == null) {
            mEntity = new SelfTeamAchieveEntity();
            mActionBar.setTitle(String.format("添加%s", getResources().getString(R.string.self_team7)));
            mBind.etStartTime.setContent("");
            mBind.etEndTime.setContent("");
        } else {
            mActionBar.setTitle(String.format("编辑%s", getResources().getString(R.string.self_team7)));
            mModel.detailTeamResults(mEntity);
        }
    }

    @Override
    protected void initView() {
        mCacheImgMap = new HashMap<>();
        mUploadImgList = new ArrayList<>();
        mUploadVideoList = new ArrayList<>();
        mEntity = (SelfTeamAchieveEntity) getIntent().getSerializableExtra(AppConstant.EXTRA_ENTITY);
        mBind = DataBindingUtil.setContentView(this, R.layout.activity_self_team_achieve_edit);
        mBind.setViewModel(mEntity);
        mBind.btnRelease.setOnClickListener(this);
        mBind.etStartTime.setOnWholeItemClickListener(this);
        mBind.etEndTime.setOnWholeItemClickListener(this);
        mBind.etAddress.setOnWholeItemClickListener(this);
        mBind.etContactPhone.setInputType(InputType.TYPE_CLASS_PHONE);
        mBind.etContactPhone.setInfilterType(ItemInputTextView.TYPE_PHONE);
        mBind.etProjectName.setInfilterType(ItemInputTextView.TYPE_NAME);
        mBind.etAddress.setInfilterType(ItemInputTextView.TYPE_NAME);
        mBind.etOwner.setInfilterType(ItemInputTextView.TYPE_NAME);
        mBind.etStartTime.setInfilterType(ItemInputTextView.TYPE_DATE);
        mBind.etEndTime.setInfilterType(ItemInputTextView.TYPE_DATE);
        mBind.etContact.setInfilterType(ItemInputTextView.TYPE_NAME);

        initPic();
        initVideo();

    }

    private void initPic() {
        List<String> tempData = new ArrayList<>();
        if (mEntity != null && !TextUtils.isEmpty(mEntity.getEvidencesImg())) {
            tempData.addAll(Arrays.asList(mEntity.getEvidencesImg().split(",")));
        }
        GridLayoutManager manager = new GridLayoutManager(this, 4);
        mBind.rvPic.setLayoutManager(manager);
        mPicAdapter = new SelfTeamPicAdapter(this, tempData, AppConstant.UPLOAD_MAX_SIZE, manager);
        mBind.rvPic.setHasFixedSize(false);
        mBind.rvPic.addItemDecoration(new GridSpacingItemDecoration(4, ScreenUtils.dip2px(this, 2), false));
        mBind.rvPic.setAdapter(mPicAdapter);
        mPicAdapter.setOnItemClick(new AdapterOnItemClick<String>() {
            @Override
            public void onItemClick(String s, int position) {
                if (TextUtils.isEmpty(s)) {
                    mModel.pictureSelector(mPicAdapter.hasCount());
                } else {
                    Intent intent = new Intent(getActivity(), PhotoViewActivity.class);
                    intent.putExtra(PhotoViewActivity.KEY_PHOTO_URLS, (Serializable) mPicAdapter.getDatas());
                    intent.putExtra(PhotoViewActivity.KEY_PHOTO_POSITION, position);
                    startActivity(intent);
                }
            }
        });
    }

    private void initVideo() {
        List<String> tempData = new ArrayList<>();
        if (mEntity != null && !TextUtils.isEmpty(mEntity.getEvidencesVideo())) {
            tempData.addAll(Arrays.asList(mEntity.getEvidencesVideo().split(",")));
        }
        mVideoAdapter = new SelfTeamVideoAdapter(this, tempData, 1);
        mBind.rvVideo.setLayoutManager(new GridLayoutManager(this, 4));
        mBind.rvVideo.setHasFixedSize(false);
        mBind.rvVideo.addItemDecoration(new GridSpacingItemDecoration(4, ScreenUtils.dip2px(this, 2), false));
        mBind.rvVideo.setAdapter(mVideoAdapter);
        mVideoAdapter.setOnItemClick(new AdapterOnItemClick<String>() {
            @Override
            public void onItemClick(String s, int position) {
                if (TextUtils.isEmpty(s)) {
                    mModel.videoSelector(mVideoAdapter.hasCount());
                } else {
                    PictureSelector.create(SelfTeamAchieveEditActivity.this).externalPictureVideo(s);
                }
            }
        });
    }

    @Override
    public void OnWholeItemClick(View v) {
        int id = v.getId();
        if (id == R.id.et_start_time) {
            mModel.showTimePop(true, 0L);
        } else if (id == R.id.et_end_time) {
            if (TextUtils.isEmpty(mBind.etStartTime.getContent())) {
                MToast.showToast(this, mBind.etStartTime.getContent_edt().getHint().toString());
                return;
            }
            mModel.showTimePop(false, mEntity.getStartTime());
        } else if (id == R.id.et_address) {
            if (addressEntityList != null) {
                showCityPop();
            } else {
                mModel.getAddressModel();
            }
        }
    }

    @Override
    public void onMultiClick(View v) {
        if (v.getId() == R.id.btn_release) {
            if (TextUtils.isEmpty(mBind.etProjectName.getContent())) {
                MToast.showToast(this, "请输入项目名称");
                return;
            }
            if (TextUtils.isEmpty(mBind.etStartTime.getContent())) {
                MToast.showToast(this, "请选择开工日期");
                return;
            }
            if (TextUtils.isEmpty(mBind.etEndTime.getContent())) {
                MToast.showToast(this, "请选择竣工日期");
                return;
            }
            if (TextUtils.isEmpty(mBind.etAddress.getContent())) {
                MToast.showToast(this, mBind.etAddress.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(mBind.etAddressDetail.getContent())) {
                MToast.showToast(this, "请输入详细地址");
                return;
            }
            if (!TextUtils.isEmpty(mBind.etContactPhone.getContent()) && !CheckUtils.isMobile(mBind.etContactPhone.getContent().trim())) {
                MToast.showToast(this, "请输入正确的联系电话");
                return;
            }
            if (TextUtils.isEmpty(mBind.etContent.getEditContent())) {
                MToast.showToast(this, "请输入施工内容");
                return;
            }
            if (TextUtils.isEmpty(mBind.etDescribe.getEditContent())) {
                MToast.showToast(this, "请输入项目描述");
                return;
            }
            mEntity.setProjectName(mBind.etProjectName.getContent());
            mEntity.setOwner(mBind.etOwner.getContent());
            mEntity.setContact(mBind.etContact.getContent());
            mEntity.setProjectPlace(mBind.etAddressDetail.getContent());
            mEntity.setMainBusiness(mBind.iitBusinessContent.getContent());
            mEntity.setBusinessDescription(mBind.etContentIntroduction.getEditContent());
            String temp = mBind.etContactPhone.getContent();
            if (mBind.etContactPhone.getContent().startsWith("+86")) {
                temp = mBind.etContactPhone.getContent().substring(3);
            }
            mEntity.setContactPhone(temp);
            mEntity.setConstruction(mBind.etContent.getEditContent());
            mEntity.setProjectDescribe(mBind.etDescribe.getEditContent());
            mUploadImgList.clear();
            mCurPicNum = -1;
            uploadPic();
        }
    }

    private void release() {
        StringBuilder sb = new StringBuilder();
        if (mUploadImgList.size() > 0) {
            for (int i = 0; i < mUploadImgList.size(); i++) {
                sb.append(mUploadImgList.get(i));
                if (i < mUploadImgList.size() - 1) {
                    sb.append(",");
                }
            }
        }
        mEntity.setEvidencesImg(sb.toString());
        mModel.addTeamResults(mEntity);

    }

    private void uploadPic() {
        mCurPicNum++;
        int size = mPicAdapter.getRealCount();
        if (size > 0 && mCurPicNum < size) {
            String path = mPicAdapter.getDatas().get(mCurPicNum);
            if (path.startsWith("http")) {
                // 保存已上传图片
                mUploadImgList.add(path);
                uploadPic();
            } else {
                // 过滤已上传的
                if (!TextUtils.isEmpty(mCacheImgMap.get(path))) {
                    mUploadImgList.add(mCacheImgMap.get(path));
                    uploadPic();
                } else {
                    File file = new File(mPicAdapter.getDatas().get(mCurPicNum));
                    mModel.uploadMultiFileModel(file, mCurPicNum + 1, size);
                }
            }
        } else {
            release();
        }
    }

    /**
     * 时间选择回调
     * @param isStart
     * @param date
     */
    public void updateStartTime(boolean isStart, Date date) {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(date);
        if (isStart) {
            mEntity.setStartTime(date.getTime());
            mBind.etStartTime.setContent(format);
        } else {
            mEntity.setEndTime(date.getTime());
            mBind.etEndTime.setContent(format);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                mPicAdapter.setPicData(selectList);
            } else if (requestCode == PictureConfig.TYPE_VIDEO) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                mModel.uploadVideo(selectList.get(0).getRealPath());
            }
        }
    }

    /**图片上传回调
     *
     * @param fromString 本地的路径
     * @param toString 返回的网络路径
     */
    public void uploadPicInfo(String fromString, String toString) {
        mUploadImgList.add(toString);
        mCacheImgMap.put(fromString, toString);
        uploadPic();
    }

    /**
     * 更新视频
     * @param videoId
     * @param filePath
     */
    public void updateVideoInfo(String videoId, String filePath) {
        runOnUiThread(() -> {
            mUploadVideoList.clear();
            mUploadVideoList.add(videoId);
            List<String> temps = new ArrayList<>();
            temps.add(filePath);
            mVideoAdapter.setData(temps);
        });
    }

    /**
     * 发布修改数据成功
     */
    public void editEntitySuccess() {
        setResult(RESULT_OK, new Intent().putExtra(AppConstant.EXTRA_OBJ, mEntity));
        finish();
    }

    /**
     * 初始化数据回调
     * @param data
     */
    public void updateOfferEntity(SelfTeamAchieveEntity data) {
        if (data != null) {
            mEntity = data;
            mBind.setViewModel(mEntity);
            List<String> tempData = new ArrayList<>();
            if (!TextUtils.isEmpty(mEntity.getEvidencesImg())) {
                tempData.addAll(Arrays.asList(mEntity.getEvidencesImg().split(",")));
            }
            mPicAdapter.setData(tempData);
            updateStartTime(true, new Date(mEntity.getStartTime()));
            updateStartTime(false, new Date(mEntity.getEndTime()));
        }
    }

    public void showEmpty() {
        mBind.emptyView.setVisibility(View.VISIBLE);
        DialogHelper.dismissProgressDialog();
    }
    //所在地区选择
    public void showAddressPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        this.addressEntityList = data;
        initJsonData();
    }
    private void initJsonData() {
        //城市列表
        @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") List<AddressEntity<List<AddressEntity>>> cityList;
        //区域列表
        List<List<AddressEntity>> areaList;
        for (int x = 0; x < addressEntityList.size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            if (mEntity != null && mEntity.getProvinceName() != null && mEntity.getProvinceName().equals(addressEntityList.get(x).getName())) {
                cityPosition1 = x;
            }
            opt2.add(addressEntityList.get(x).getChildren());
            for (int i = 0; i < addressEntityList.get(x).getChildren().size(); i++) {
                cityList.add(addressEntityList.get(x).getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (addressEntityList.get(x).getChildren().get(i).getChildren() == null
                        || addressEntityList.get(x).getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(addressEntityList.get(x).getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        if (mEntity != null) {
            if (mEntity.getCityName() != null) {
                for (int x2 = 0; x2 < opt2.size(); x2++) {
                    if (mEntity.getCityName().equals(addressEntityList.get(cityPosition1).getChildren().get(x2).getName())) {
                        cityPosition2 = x2;
                        break;
                    }
                }
            }
            if (mEntity.getAreaName() != null) {
                for (int x3 = 0; x3 < opt3.size(); x3++) {
                    if (mEntity.getAreaName().equals(addressEntityList.get(cityPosition1).getChildren().get(cityPosition2).getChildren().get(x3).getName())) {
                        cityPosition3 = x3;
                        break;
                    }
                }
            }
        }
        showCityPop();
    }

    public void showCityPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(this, (options1, options2, options3, v) -> {
            String areaName;
            if (opt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
            } else {
                areaName = opt3.get(options1).get(options2).get(options3).getName();
                cityPosition3 = options3;
                mEntity.setDistrictNo(opt3.get(options1).get(options2).get(options3).getNo());
                mEntity.setAreaName(areaName);
            }
            String content = addressEntityList.get(options1).getName()
                    + opt2.get(options1).get(options2).getName()
                    + areaName;
            mBind.etAddress.setContent(content);
            cityPosition1 = options1;
            cityPosition2 = options2;
            mEntity.setProvinceName(addressEntityList.get(options1).getName());
            mEntity.setProvinceNo(addressEntityList.get(options1).getId());
            mEntity.setCityName(opt2.get(options1).get(options2).getName());
            mEntity.setCityNo(opt2.get(options1).get(options2).getNo());
        }).setCancelColor(ContextCompat.getColor(this, R.color.color_666666)).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }
}
